package io.gitee.zhangbinhub.acp.boot.socket.udp

import io.gitee.zhangbinhub.acp.boot.log.LogAdapter
import io.gitee.zhangbinhub.acp.boot.socket.base.BaseSocketServerAdapter
import io.gitee.zhangbinhub.acp.boot.socket.base.SocketServerHandle
import io.gitee.zhangbinhub.acp.boot.socket.conf.SocketListenerConfiguration
import io.netty.buffer.ByteBuf
import io.netty.buffer.Unpooled
import io.netty.channel.ChannelHandlerContext
import io.netty.channel.socket.DatagramPacket

/**
 * Udp 报文处理
 *
 * @since JDK 17
 */
class UdpServerAdapter internal
constructor(
    logAdapter: LogAdapter,
    socketListenerConfiguration: SocketListenerConfiguration,
    socketServerHandle: SocketServerHandle
) : BaseSocketServerAdapter(logAdapter, socketListenerConfiguration, socketServerHandle) {

    override fun beforeReadMessage(msg: Any): ByteBuf = (msg as DatagramPacket).content()

    override fun afterSendMessage(ctx: ChannelHandlerContext) {}

    override fun afterReadMessage(ctx: ChannelHandlerContext) {}

    @Throws(Exception::class)
    override fun beforeSendMessage(ctx: ChannelHandlerContext, requestMsg: Any?, sendStr: String): Any {
        val packet = requestMsg as DatagramPacket?
        return DatagramPacket(
            Unpooled.copiedBuffer(sendStr.toByteArray(charset(socketListenerConfiguration.charset))),
            packet!!.sender()
        )
    }

}
